package com.yyb.exception;

import com.yyb.common.Result;
import com.yyb.enums.ResultEnums;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 描述: [全局异常处理器]
 * 
 * 
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理IllegalArgumentException
     */
    @ExceptionHandler(value = {IllegalArgumentException.class})
    public Result<String> illegalArgumentException(IllegalArgumentException e) {
        return new Result<>(ResultEnums.ERROR, e.getMessage());
    }

    /**
     * 处理前端传来的数据不合法的问题
     */
    @ExceptionHandler(value = {BindException.class})
    public Result<String> bindException(BindException e) {
        List<ObjectError> allErrors = e.getAllErrors();
        StringBuffer errors = new StringBuffer();
        for (ObjectError allError : allErrors) {
            errors.append(allError.getDefaultMessage()+",");
        }
        return new Result<>(ResultEnums.PARAMS_ERROR, errors.toString());
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(value = {BusinessException.class})
    public Result<String> businessException(BusinessException e) {
        return new Result<>(ResultEnums.ERROR.getCode(), e.getMessage());
    }
}
